package 回溯;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author aodre , QQ : 480029069
 * @date 2023/2/2 10:51
 */
public class leetcode93ip地址New {
    /*
    2023/2/2
    现在 再去写 这个题 ，那就 变得 十分的 简单了！
    下面是 不采用 StringBuilder的写法
    2ms
     */

    public void recursion(int index, Deque<String> path, List<String> ans,String s){
        if(index == s.length() && path.size() == 4){
            ans.add(String.join(".",path));
            return ;
        }
        if(index == s.length() || path.size() == 4 ){
            return ;
        }
        for(int i = index + 1;i <= s.length() && i - index <= 3;i++){
            String temp = s.substring(index,i);
            if(judge(temp)){
                path.addLast(temp);
                recursion(i,path,ans,s);
                path.removeLast();
            }
        }
    }

    public boolean judge(String s){
        if(s.charAt(0) == '0' && s.length() > 1){
            return false;
        }
        int judge = Integer.parseInt(s);
        return judge>= 0 && judge <= 255 ;
    }

    public List<String> solution(String s){
        int len = s.length();
        List<String> ans = new ArrayList<>();
        if(len < 4 || len > 12){
            return ans;
        }
        Deque<String> path = new ArrayDeque<>();
        recursion(0,path,ans,s);
        return ans;
    }

    public static void main(String[] args) {
        String s = "0023";
        System.out.println(Integer.parseInt(s));
    }


    /*
     下面是 采用 StringBuilder 的写法
     1ms
     */
    public void recursion1(int index, StringBuilder sb,int count, List<String> ans,String s){
        if(index == s.length() && count == 4){
            // 把 最后多 添加的 一个点  ** 。** 给删掉
            sb.deleteCharAt(sb.length() - 1);
            ans.add(sb.toString());
            return ;
        }
        if(index == s.length() || count == 4 ){
            return ;
        }
        for(int i = index + 1;i <= s.length() && i - index <= 3;i++){
            String temp = s.substring(index,i);
            if(judge(temp)){
                int len1 = sb.length();
                sb.append(temp).append(".");
                recursion1(i,sb,count + 1,ans,s);
                int len2 = sb.length();
                // backTracing
                sb.delete(len1,len2);
            }
        }
    }

}
